package com.example.exam.service.impl;

import com.example.exam.config.SystemConfig;
import com.example.exam.pojo.entity.TUser;
import com.example.exam.service.IAuthenticationService;
import com.example.exam.service.IUserService;
import com.example.exam.tools.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author LENOVO
 * @description TODO
 * @date 2023/2/3 21:41
 */
@Service
public class AuthenticationServiceImpl implements IAuthenticationService {
    @Autowired
    private IUserService userService;
    @Autowired
    private  SystemConfig systemConfig;


    /**
     * @param username username
     * @param password password
     * @return boolean
     */
    @Override
    public boolean authUser(String username, String password) {
        TUser user = userService.getUserByUserName(username);
        return authUser(user, username, password);
    }


    @Override
    public boolean authUser(TUser user, String username, String password) {
        if (user == null) {
            return false;
        }
        String encodePwd = user.getPassword();
        if (null == encodePwd || encodePwd.length() == 0) {
            return false;
        }
        String pwd = pwdDecode(encodePwd);
        return pwd.equals(password);
    }

    @Override
    public String pwdEncode(String password) {
        return RsaUtil.rsaEncode(systemConfig.getPwdKey().getPublicKey(), password);
    }

    @Override
    public String pwdDecode(String encodePwd) {
        return RsaUtil.rsaDecode(systemConfig.getPwdKey().getPrivateKey(), encodePwd);
    }

}
